Ext.namespace("Utils");

Utils.SEPARATOR = "`^";
Utils.SUB_SEPARATOR = "^`";

Utils.getMap = function(p) {
	var result = {};
	if (typeof p !== 'string') return result;
	var list = p.split(Utils.SEPARATOR);
	var m = null;
	for(var i=0,l; l=list[i++];) {
		m = l.split(Utils.SUB_SEPARATOR);
		result[m[0]] = m[1];
	}
	return result;
};
/**
 * add by wilson formatdate('yyyy-MM-dd')
 */
 Utils.formatDate=function(data,idx,pattern){
 	if(pattern==null)
 		pattern='Y-m-d'; 	
 	if(data[idx]!=null){
 		data[idx]=Ext.util.Format.date(data[idx],pattern);
 	}
 	return data;
 }
 Utils.getNameFromStore=function(value,store){
 	var count=store.getCount(); 	
	for(var i=0 ;i<count;i++){
		var data=store.getAt(i).data;
		if(data['value']==value) 
			return data['name'];
	};
 }
Utils.msg = function(title, msg, icon) {
	Ext.MessageBox.show({
		title: title,
		msg: msg,
		buttons: Ext.MessageBox.OK,
		closable: false,
		icon: icon
	});
};
Utils.info = function(msg, title) {
	Utils.msg( (!title) ? '系统提示' : title, msg, Ext.MessageBox.INFO);
};
Utils.warn = function(msg, title) {
	Utils.msg( (!title) ? '系统提示' : title, msg, Ext.MessageBox.WARNING);
};
Utils.error = function(msg, title) {
	Utils.msg( (!title) ? '系统提示' : title, msg, Ext.MessageBox.ERROR);
};
Utils.connectionError = function() {
	Utils.error('连接失败', '连接服务器失败。请稍候再试！');
};
Utils.confirm = function(o) {
	Ext.MessageBox.confirm('系统提示', o.msg, function(e) {
		if (e == 'yes') {
			if (o.success)
				o.success();
		} else {
			if (o.cancel)
				o.cancel();
		}
	}, o.scope);
};
/**
 * add by wangwei
 */
Utils.msg2=function(msg,icon,width,title){
	Ext.MessageBox.show({
       title: (title==null?'系统提示':title),
       msg:(msg==null?'操作成功':msg),
       width:(width==null?130:width),
       buttons: Ext.MessageBox.OK,
       closable: false,
       icon:icon
   });
};

Utils.info2 = function(msg,width, title) {
	Utils.msg2(msg,Ext.MessageBox.INFO,width,title);
};
Utils.warn2 = function(msg,width, title) {
	Utils.msg2(msg, Ext.MessageBox.WARNING,width,title);
};
Utils.error2 = function(msg,width, title) {
	Utils.msg2(msg, Ext.MessageBox.ERROR,width,title);
};

Utils.confirm2=function(o){//msg,width,fn,title
	Ext.MessageBox.show({
       title: (o.title==null?'系统提示':o.title),
       msg:(o.msg==null?'操作成功':o.msg),
       width:(o.width==null?300:o.width),
       buttons: Ext.MessageBox.YESNO,
       icon: Ext.MessageBox.QUESTION,
       fn:function(btn){
			if(btn=='yes')o.fn();
		}
   });
};
Utils.notification = function(o) {	// request Ext.ux.Notification.js
	if (typeof o === 'string') {
		o = {message: o};
	}
	new Ext.ux.Notification({
		iconCls: 'x-icon-information',
		title: o.title || '系统提示',
		html: o.message || '',
		autoDestory: o.destory || true,
		hideDelay: o.delay || 5000
	}).show(document);
};

Utils.regError = new RegExp("\\t.*\n", "g");
Utils.regHTML = /<[^>].*?>/g;

Utils.prepareError = function(txt) {
	return txt.replace(Utils.regError, '');
};
Utils.getHTMLData = function(s) {
    return s.replace(Utils.regHTML, '');
};
Utils.getSubHTMLData = function(s,length){
	s = Utils.getHTMLData(s);
	return s.substring(0,length)+'....';
}

Utils.clone = function(o) {
	if (!o || 'object' !== typeof o) {
		return o;
	}
	var c = '[object Array]' === Object.prototype.toString.call(o) ? [] : {};
    var p, v;
    var p, v;
    for(p in o) {
        if(o.hasOwnProperty(p)) {
            v = o[p];
            if(v && 'object' === typeof v) {
                c[p] = Ext.ux.clone(v);
            } else {
                c[p] = v;
            }
        } // End If
    }   // End for
    return c;
};	// End Clone 

Utils.justRequest = function(conn, o) {
	conn.request({
		callback: function(a, s, r) {
			if (r.status >= 400)
				Utils.error(r.statusText, Utils.prepareError(r.responseText));
		},
		success: function(resp, action) {
			var data = Ext.util.JSON.decode(resp.responseText);
            if (data && data.success === "false") {
            	Utils.error( Utils.prepareError(data.error),"错误");
            	if (o.failture)
            		o.failture(data, action);
            }
		},
		failture: function(resp, action) {
			if (o.failture) o.failture();
            if (action.failureType == 'connect')
            	Utils.connectionError();
            else
            	Utils.error("失败", "[错误类型=" + action.failureType + "] 请联系管理员!");
		}
	});
};
Utils.getJson = function(o){
	var array = [];
	if(!o)
		return [];
	if(o){
		for(var a in o){
			var b ={};
			b.value = a
			b.name = o[a];
			array.push(b);
		}
		
	}
}
Utils.request = function(conn, o) {
	var cn = typeof conn === 'string' ? new Ext.data.Connection({url: conn}) : conn;
	cn.request({
		params: o.params,
		caller: o.caller,
		callback: function(a, s, r) {
			if (o.after) o.after();
			if (r.status <= 0)
				Utils.error("连接失败", "连接超时，请检查网络!");
			else if (r.status >= 400)
				Utils.error(r.statusText, Utils.prepareError(r.responseText));
		},
		success: function(resp, action) {
			var data = Ext.util.JSON.decode(resp.responseText);
            if (data && data.success === "true") {
            	if (o.success)
            		o.success(data, action);
            } else {
            	Utils.error( Utils.prepareError(data.error),"错误");
            	if (o.failture)
            		o.failture(data, action);
            }
		},
		failture: function(resp, action) {
			if (o.failture) o.failture();
            if (action.failureType == 'connect')
            	Utils.connectionError();
            else
            	Utils.error("失败", "[错误类型=" + action.failureType + "] 请联系管理员!");
		}
	});
};

Utils.getParameter = function(item) {
    var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)","i"));
    return svalue ? svalue[1] : svalue;
};

Utils.openWindow = function(url, name) {
	window.open(url, name, 'status=no,toolbar=no,menubar=no');
};

Utils.getParent = function() {
	if (parent == window) return null;
	return parent;
};

// extends Ext
Ext.apply(Ext.form.VTypes, {
    daterange : function(val, field) {
        var date = field.parseDate(val);

        if(!date){
            return;
        }
        if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
            var start = Ext.getCmp(field.startDateField);
            start.setMaxValue(date);
            start.validate();
            this.dateRangeMax = date;
        } 
        else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
            var end = Ext.getCmp(field.endDateField);
            end.setMinValue(date);
            end.validate();
            this.dateRangeMin = date;
        }
        /*
         * Always return true since we're only using this vtype to set the
         * min/max allowed values (these are tested for after the vtype test)
         */
        return true;
    }
});

Utils.formatURL = function(url) {
	var result = [url];
	if (url.indexOf('?') != -1) result.push('&');
	else result.push('?');
	result.push('timesnap=');
	result.push(Date.parse(new Date()));
	return result.join('');
};

Utils.getNextDate = function(t) {
	var d = new Date();
	var result = [];
	switch(t) {
	case 'w': 
		var added = d.getDay() === 0 ? 1 : 6;
		d = d.add(Date.DAY, added);
		result.push(d);
		d = d.add(Date.DAY, 6);
		result.push(d);
		break;
	case 'm':
		d = d.add(Date.MONTH, 1);
		result.push(d.getFirstDateOfMonth(), d.getLastDateOfMonth());
		break;
	case 'd':
		return d.add(Date.DAY, 1);
		break;
	}
	return result;
};

Utils.DEBUG = true;
Utils.debug = function(msg) {
	if (!console || !Utils.DEBUG) return;
	console.debug(msg);
};

Utils.getUserName = function(userNames){
	var userMap = {};
	for(var i=0,user;user=userNames[i++];){
		userMap[user.USER_ID] = user.USER_NAME;
	}
	return userMap;
};

Utils.getUser = function(ids,userMap){
	if(ids == undefined)
		return "";
	var users = ids.split(",");
	var res = "";
	for(var i=0,user;user=users[i++];){
		if(userMap[user]==undefined){
			return "";
		}
		res = res + userMap[user] + ";";
	}
	return res;
};
